package club.itstudio.IContainer.controller.common;

import club.itstudio.IContainer.annotation.RecaptchaRequired;
import club.itstudio.IContainer.entity.User;
import club.itstudio.IContainer.exception.BaseException;
import club.itstudio.IContainer.exception.ParamInvalidException;
import club.itstudio.IContainer.service.RecaptchaService;
import club.itstudio.IContainer.service.UserService;
import club.itstudio.IContainer.util.Hash;
import club.itstudio.IContainer.util.Result;
import club.itstudio.IContainer.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/register")
public class RegisterController {
    private UserService userService;
    private RecaptchaService recaptchaService;

    @Autowired
    public void setRecaptchaService(RecaptchaService recaptchaService) {
        this.recaptchaService = recaptchaService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public void toStudentRegisterPage(HttpServletResponse response) throws IOException {
        response.sendRedirect("/html/student/register.html");
    }

    @PostMapping
    @RecaptchaRequired
    public Result registerNewUser(@RequestParam String username, @RequestParam String password) {
        if (username == null || password == null) throw new ParamInvalidException();
        if (username.length() < 5 || username.length() > 30) throw new ParamInvalidException();
        if (password.length() < 6 || password.length() > 30) throw new ParamInvalidException();

        User user = userService.getByUserName(username);
        if (user != null) {
            throw new BaseException(400, "用户已存在");
        }

        User newUser = new User();
        newUser.userName = username;
        newUser.password = Hash.SHA256(password);
        newUser.userType = 2;
        newUser.createdTime = System.currentTimeMillis();
        boolean success = userService.insert(newUser);
        if (success){
            return ResultUtil.success();
        }else {
            throw new BaseException("注册失败，请稍后再试");
        }

    }
}
